<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="24">
            <a-form-model-item label="类目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.name" dictCode="category_name" placeholder="请选择类目名称" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="计算公式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="computingFormula">
              <div class="computing_box" :class="formDisabled ? 'onlyRead' : ''">
                <div class="computing_info" v-for="(item, key) in salaryFormula" :key="key">
                  <div class="computing_name">
                    {{item.name}}
                  </div>
                  <div class="computing_close" @click="closeClick(key)">
                    <a-icon type="close" />
                  </div>
                </div>
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <div class="salary_box salarydist" :class="formDisabled ? 'onlyRead' : ''">
              <div class="salary_box_info salary" v-for="(item, key) in dictOptions" :key="key" @click="salaryClick(item,key)">
                {{ item.name }}
              </div>
            </div>
          </a-col>
          <a-col :span="4" style="padding:0">
            <div class="salary_box salary_info" :class="formDisabled ? 'onlyRead' : ''">
              <div class="salary_box_info operator" v-for="(item, key) in operatorData" :key="key" @click="salaryClick(item,key)">
                {{ item.name }}
              </div>
            </div>
            <a-button :class="formDisabled ? 'onlyRead' : ''" class="salary_button" type="primary" @click="checkClick">
              检测
            </a-button>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depict">
              <a-textarea :disabled="formDisabled" v-model="model.depict" rows="4" placeholder="请输入描述"  :max-length="500"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea :disabled="formDisabled" v-model="model.remark" rows="4" placeholder="请输入备注" :max-length="500" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'ErpRemunerationCategoryDefinitionForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        flag: true,
        dictOptions: [],
        model:{
         },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
        name: [
            { required: true, message: '请输入类目名称!'},
            { validator: (rule, value, callback) => validateDuplicateValue('erp_remuneration_category_definition', 'name', value, this.model.id, callback)},
        ],
        computingFormula: [
            { required: true, validator: (rule, value, callback) => {
              if(this.model.computingFormula) {
                callback()
              } else {
                this.flag = true
                callback("请输入计算公式!")
              }
            }}
        ],
        depict: [
            { required: true, message: '请输入描述!'},
        ],
        },
        url: {
          listDetails: "/api/erp/hr/payment/erpRemunerationProjectDefinition/listDetails",
          add: "/api/erp/hr/payment/erpRemunerationCategoryDefinition/add",
          edit: "/api/erp/hr/payment/erpRemunerationCategoryDefinition/edit",
          queryById: "/api/erp/hr/payment/erpRemunerationCategoryDefinition/queryById",
          checkOperation: "/api/erp/hr/payment/erpRemunerationCategoryDefinition/checkOperation"
        },
        salaryFormula: [],
        operatorData: [
          {
            id: 1,
            name: "+",
            type: 'add',
            other: 'operator'
          },
          {
            id: 2,
            name: "-",
            type: 'plus',
            other: 'operator'
          },
          {
            id: 3,
            name: "*",
            type: 'ride',
            other: 'operator'
          },
          {
            id: 4,
            name: "/",
            type: 'except',
            other: 'operator'
          },
          {
            id: 5,
            name: "(",
            type: 'leftBracket',
            other: 'operator'
          },
          {
            id: 6,
            name: ")",
            type: 'rightBracket',
            other: 'operator'
          },
        ]
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.findDictOptions()
    },
    methods: {
      checkClick() {
        this.confirmLoading = true;
        const that = this
        const computingFormula = this.calculate()
        //访问后台校验计算公式是否正确
        getAction(this.url.checkOperation, { computingFormula }).then((res) => {
          if (res.success) {
            that.flag = false
            that.$message.success(res.result);
          } else {
            that.flag = true
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.confirmLoading = false;
        })
      },
      calculate() {
        let centerData = []
        this.salaryFormula.forEach((item,index)=>{
          if(item.other=='number') {
            centerData.push(item.id)
          }
          if(item.other=='operator') {
            centerData.push(item.name)
          }
        })
        this.model.computingFormula = centerData.toString()
        return this.model.computingFormula;
      },
      closeClick(key) {
        this.flag = true
        this.salaryFormula.splice(key,1)
      },
      salaryClick(item,key) {
        if(this.salaryFormula.length>0) {
          if(this.salaryFormula.length==1) {
            if(this.salaryFormula[0].other=='operator'&&item.other=='operator') {
              this.$message.warning('请按正常运算方式点击运算符');
              return ;
            }
            if(this.salaryFormula[this.salaryFormula.length-1].other=='number'&&item.other=='number') {
              this.$message.warning('请按正常运算方式点击运算符');
              return ;
            }

          } else {
            if(this.salaryFormula[this.salaryFormula.length-1].other=='number'&&item.other=='number') {
              this.$message.warning('请按正常运算方式点击运算符');
              return ;
            } else if(this.salaryFormula[this.salaryFormula.length-1].other=='operator' && this.salaryFormula[this.salaryFormula.length-1].type!='rightBracket' && item.type=='plus') {
              this.$message.warning('请按正常运算方式点击运算符');
              return ;
            }
          }
          this.salaryFormula.push(item)
        } else {
          if(item.type=='leftBracket'||item.type=='number') {
            this.salaryFormula.push(item)
          } else {
            this.$message.warning('请按正常运算方式点击运算符');
          }

        }
        this.flag = true
      },
      findDictOptions() {
        const that = this
        getAction(that.url.listDetails).then((res)=>{
        if(res.success){
          res.result.forEach((item,index)=>{
            item.type='number'
            item.other='number'
          })
          that.dictOptions = res.result
          that.dictOptions.push({id: '0', name: '无', type: 'number', other: 'number'})
        }else{
          that.$message.warning(res.message);
        }
      })
      },
      add () {
        this.salaryFormula = []
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        if(this.model.computingFormulaJson) {
          this.salaryFormula = JSON.parse(this.model.computingFormulaJson)
        }
        this.visible = true;
      },
      submitForm () {
        this.calculate()
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if(this.model.computingFormula  && this.flag) {
            this.$message.warning('请先点击检测按钮对计算公式进行校验');
            return
          }
          if (valid) {
            that.confirmLoading = true;
            this.model.computingFormulaJson = JSON.stringify(this.salaryFormula)
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
    }
  }
</script>

<style scoped>
  .operator {
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #eee;
    margin-bottom: 5px;
    font-size: 14px;
    font-weight: bold;
    cursor: pointer;
    height: 25px;
    width: 38px;
    margin-right: 10px;
    margin-bottom: 14px;
    border-radius: 5px;
  }
  .salary_box {
    margin-top: 35px;

  }
  .salary_info {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
  }
  .salarydist {
    overflow-y: scroll;
    border: 1px solid #eee;
    height: 168px;
  }
  .computing_box {
    min-height: 150px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    height: 165px;
    display: flex;
    align-items: center;
    align-content: flex-start;
    flex-wrap: wrap;
    padding: 5px;
    box-sizing: border-box;

  }
  .computing_info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border: 1px solid #eee;
    height: 30px;
    border-radius: 20px;
    padding: 0 10px;
    box-sizing: border-box;

  }
  .computing_name {
    height: 100%;
    display: flex;
    align-items: center;
    margin-right: 5px;
    color: #333;
    height: 30px;
  }
  .computing_close {
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 5px;
    cursor: pointer;
    border-radius: 50%;
    border: 1px solid #eee;

  }
  .salary {
    cursor: pointer;
    padding: 0 5px;
    box-sizing: border-box;
  }
  .salary:hover {
    background-color: #eee;
  }
  .salary_button {
    width: 86px;
    height: 50px;
    background-color: rgba(129, 211, 248, 1);
    box-sizing: border-box;
    border-radius: 5px;
    border: 1px solid #eee;
    color: #000;
  }
  .onlyRead {
    pointer-events: none;
  }
</style>
